package cn.com.scooper.utils;

import cn.com.scooper.dao.xf.ConfigNameDao;
import cn.com.scooper.utils.sm2.SM2EncryptUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static cn.com.scooper.common.constant.CommonMineConstant.*;

/**
 * @author lijuntao
 * @version 1.0
 * @date 2023/11/8 15:34
 * 矿山市级请求工具
 */
@Component
public class MineCityRequestUtils {
    private static Logger logger = LoggerFactory.getLogger(MineCityRequestUtils.class);

    /**
     * 保存令牌map，为防止过期。每6小时刷新一次
     */
    private static final Map<String, String> JWT_MAP = new HashMap<>();

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ConfigNameDao configNameDao;

    public void getJwtToken(){
        restTemplate.getMessageConverters().add(0,new StringHttpMessageConverter(StandardCharsets.UTF_8));
        //获取登录token
        String userInfo = configNameDao.getConfigValueByKey("mine.user.info");
        if (userInfo == null){
            logger.info("矿山同步账号配置为空");
            return;
        }

        JSONObject userObject = JSONObject.parseObject(userInfo);
        String userName = userObject.getString("userName");
        String password;
        try {
            password = SM2EncryptUtil.encrypt(userObject.getString("password"));
        } catch (Exception e) {
            logger.error("【获取token】失败，加密异常{}",userInfo);
            return;
        }
        JSONObject param = new JSONObject();
        param.put("userName",userName);
        param.put("password",password);

        HttpHeaders heard = new HttpHeaders();
        heard.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<>(param.toJSONString(), heard);

        logger.info("【获取token】入参{}", JSON.toJSONString(entity));
        String response = null;
        try {
            response = restTemplate.postForObject(CITY_USER_LOGIN_URL, entity, String.class);
        }catch (Exception e){
            logger.error("【获取token】接口请求异常");
            return;
        }
        if (StringUtils.isEmpty(response)) {
            logger.error("【获取token】接口请求失败：结果为空#");
            return;
        }
//        response = new String(response.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        logger.info("【获取token】接口请求响应***" + response);
        JSONObject responseObj = JSONObject.parseObject(response);
        if ("200".equals(responseObj.getString("code"))) {
            String data = responseObj.getString("data");
            if (StringUtils.isEmpty(data)){
                logger.error("【获取token】接口异常：data结果为空");
                return;
            }
            JSONObject dataObj = JSONObject.parseObject(data);
            JWT_MAP.put("token",dataObj.getString("token"));
        }
    }

    /**
     * 保存矿山基础数据
     * @param jsonBody
     * @return
     */
    public static String mineAndDeviceReport(String jsonBody, RestTemplate restTemplate, String requestName, String url){
        restTemplate.getMessageConverters().add(0,new StringHttpMessageConverter(StandardCharsets.UTF_8));
        logger.info("进入保存" + requestName);
        String token = JWT_MAP.get("token");

        HttpHeaders heard = new HttpHeaders();
        heard.set("Authorization",token);
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        heard.setContentType(type);
        HttpEntity<String> entity = new HttpEntity<>(jsonBody, heard);

        System.out.println(jsonBody);
        System.out.println(heard);
        String response;
        try {
            response = restTemplate.postForObject(url, entity, String.class);
        } catch (RestClientException e) {
            logger.error("【上报" + requestName + "】接口请求异常");
            return null;
        }
        if (StringUtils.isEmpty(response)) {
            logger.error("【上报" + requestName + "】接口请求失败：结果为空#");
            return null;
        }
//        response = new String(response.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        logger.info("【上报" + requestName + "】接口请求响应***" + response);
        JSONObject responseObj = JSONObject.parseObject(response);
        return responseBuild(requestName, responseObj);
    }

    public static String mineAndDeviceReportGet(RestTemplate restTemplate, String requestName, String url){
        restTemplate.getMessageConverters().add(0,new StringHttpMessageConverter(StandardCharsets.UTF_8));
        String token = JWT_MAP.get("token");

        HttpHeaders heard = new HttpHeaders();
        heard.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        heard.set("Authorization",token);
        HttpEntity<String> entity = new HttpEntity<>(heard);

        System.out.println(heard);

        ResponseEntity<String> response;
        try {
            response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        }catch (Exception e){
            logger.error("【上报" + requestName + "】接口请求异常");
            return null;
        }

        if (!response.getStatusCode().equals(HttpStatus.OK)){
            logger.error("【上报" + requestName + "】接口请求失败：结果为空#");
            return null;
        }

        String body = response.getBody();
        if (body == null){
            logger.error("【上报" + requestName + "】接口请求失败：body结果为空#");
            return null;
        }
        logger.info("【上报" + requestName + "】接口请求响应***" + body);
//        JSONObject responseObj = JSONObject.parseObject(new String(body.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
        JSONObject responseObj = JSONObject.parseObject(body);
        return responseBuild(requestName, responseObj);
    }

    private static String responseBuild(String requestName, JSONObject responseObj) {
        if ("200".equals(responseObj.getString("code"))) {
            String data = responseObj.getString("data");
            if (StringUtils.isEmpty(data)){
                logger.error("【上报" + requestName + "】接口异常：data结果为空");
                return null;
            }
            return data;
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(UUID.randomUUID());
    }
}
